package com.anyi.controller;


import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.SecureUtil;
import com.anyi.common.lang.Result;
import com.anyi.dto.LoginDto;
import com.anyi.entity.Article;
import com.anyi.entity.SysUser;
import com.anyi.service.ArticleService;
import com.anyi.service.SysUserService;
import com.anyi.util.JwtUtils;
import com.anyi.util.MyUtils;
import com.anyi.util.RedisUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.java.Log;
import org.apache.catalina.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Set;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author anyi
 * @since 2022-04-14
 */
@RestController
@RequestMapping("/user")
public class SysUserController {
    @Autowired
    SysUserService sysUserService;
    @Autowired
    ArticleService articleService;

    @Autowired
    RedisUtil redisUtil;
    /**
     * 登录
     */
    @Autowired
    JwtUtils jwtUtils;
    @CrossOrigin
    @PostMapping("/login")
    public Result login(@Validated @RequestBody LoginDto loginDto, HttpServletResponse response){
        SysUser sysUser = sysUserService.getOne(new QueryWrapper<SysUser>().eq("account", loginDto.getAccount()));
        Assert.notNull(sysUser,"用户不存在");
        if (!sysUser.getPassword().equals(SecureUtil.md5(loginDto.getPassword()))){
            return Result.fail("密码错误");
        }
        // 生成一个jwt
        String jwt = jwtUtils.generateToken(sysUser.getId());
        // 将jwt写入请求头中
        response.setHeader("Authorization",jwt);
        response.setHeader("Access-Control-Expose-Headers", "Authorization");

        return Result.success(MapUtil.builder()
                .put("id",sysUser.getId())
                .put("account",sysUser.getAccount())
                .put("username",sysUser.getUsername())
                .put("email",sysUser.getEmail())
                .put("avatar",sysUser.getAvatar())
                .map()
        );
    }

    /**
     * 退出
     * @return
     */
    @RequiresAuthentication
    @GetMapping("/layout")
    public Result layout(){
        SecurityUtils.getSubject().logout();
        return Result.success(null);
    }

    /**
     * 根据id获取用户
     * @param id
     * @return
     */
    @RequiresAuthentication
    @RequestMapping("/{id}")
    public Result getUser(@PathVariable("id")Integer id){
        SysUser byId = sysUserService.getById(id);
        return Result.success(byId);
    }

    /**
     * 注册
     * @param sysUser
     * @return
     */
    @PostMapping("/save")
    public Result save(@Validated @RequestBody SysUser sysUser){
        // 未完成
        return Result.success(sysUser);
    }

    /**
     * 获取个人简介文章
     * @return
     */
    @GetMapping("/me")
    public Result userMe(){
        Article article = articleService.getOne(new QueryWrapper<Article>().eq("id", 1));
        Integer id =1;
        redisUtil.zIncrementScore("viewCounts",id.toString(),1);
        Set<ZSetOperations.TypedTuple<String>> viewCounts = redisUtil.zReverseRangeWithScores("viewCounts", 0, 10);
        Set<ZSetOperations.TypedTuple<String>> likeCounts = redisUtil.zReverseRangeWithScores("likeCounts", 0, 10);
        Article articles = MyUtils.tranFormOneView(viewCounts, article,"viewCounts");
        Article finalArticle = MyUtils.tranFormOneView(likeCounts, articles,"likeCounts");
        return Result.success(finalArticle);
    }
}
